//
//  UUCarStateListVC.m
//  UUCharterSupplier
//
//  Created by ZhangAo on 23/01/2018.
//  Copyright © 2018 UUCharter. All rights reserved.
//

#import "UUCarStateListVC.h"
#import "UUBaseTableViewCell.h"
#import "UUCarEditVC.h"
#import "UUCarManager.h"
#import "UUFleetManager.h"
#import "UUPermissionManager.h"

@interface UUCarStateListCell : UUBaseTableViewCell

@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, strong) UILabel *numberLabel;
@property (nonatomic, strong) UILabel *fleetLabel;
@property (nonatomic, strong) UILabel *selfLabel;

@end

@implementation UUCarStateListCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.nameLabel = [UILabel new];
        self.nameLabel.font = [UIFont systemFontOfSize:16];
        [self.contentView addSubview:self.nameLabel];
        [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(15);
            make.leading.mas_equalTo(15);
            make.height.mas_equalTo(22);
        }];
        
        self.numberLabel = [UILabel new];
        self.numberLabel.font = [UIFont systemFontOfSize:14];
        [self.contentView addSubview:self.numberLabel];
        [self.numberLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.equalTo(self.nameLabel);
            make.top.equalTo(self.nameLabel.mas_bottom).offset(10);
            make.height.mas_equalTo(20);
        }];
        
        self.fleetLabel = [UILabel new];
        self.fleetLabel.font = [UIFont systemFontOfSize:14];
        self.fleetLabel.textColor = COMMON_TEXT_LIGHT_COLOR;
        [self.contentView addSubview:self.fleetLabel];
        [self.fleetLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.equalTo(self.numberLabel);
            make.top.equalTo(self.numberLabel.mas_bottom).offset(10);
            make.height.mas_equalTo(20);
        }];
        
        self.selfLabel = [UILabel new];
        self.selfLabel.font = self.fleetLabel.font;
        self.selfLabel.textColor = self.fleetLabel.textColor;
        [self.contentView addSubview:self.selfLabel];
        [self.selfLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.trailing.mas_equalTo(-15);
            make.top.equalTo(self.nameLabel);
            make.height.mas_equalTo(20);
        }];
    }
    return self;
}

@end

////////////////////////////////////////////////////////////

@interface UUCarStateListVC () <UITableViewDelegate, UITableViewDataSource, UUCarManagerObserver>

@property (nonatomic, assign) UUCarReviewStatus status;
@property (nonatomic, copy) NSArray<NSNumber *> *cars;

@end

@implementation UUCarStateListVC

+ (instancetype)listWithStatus:(UUCarReviewStatus)status {
    UUCarStateListVC *listVC = [self instanceOfAppropriate];
    listVC.status = status;
    return listVC;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.backgroundColor = COMMON_BACKGROUND_COLOR;
    [self.tableView registerClass:[UUCarStateListCell class] forCellReuseIdentifier:@"Cell"];
    
    [self reloadCars];
    
    [GetCarManager() addObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)reloadCars {
    self.cars = [GetCarManager() fetchCarsForStatus:self.status
                    greaterThanOrEqualToCarCategory:self.greaterThanOrEqualToCarCategory
                                            fleetId:self.fleetId];
    [self.tableView reloadData];
}

#pragma mark - UITableViewDelegate, UITableViewDataSource methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.cars.count;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 105;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UUCarStateListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    
    NSNumber *carId = self.cars[indexPath.row];
    UUCarModel *car = [GetCarManager() fetchCarWithCarId:carId];
    
    cell.numberLabel.text = car.carNum;
    
    UUCarCategoryModel *categoryModel = [GetCarCategoryManager() fetchCarCategoryWithCategoryId:car.carType];
    cell.nameLabel.text = categoryModel.name;
    
    UUFleetModel *fleet = [GetFleetManager() fetchFleetWithFleetId:car.fleetId];
    cell.fleetLabel.text = fleet.name;
    
    cell.selfLabel.text = car.isSelf ? @"自营" : @"挂靠";
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSNumber *carId = self.cars[indexPath.row];
    
    if (self.didSelectCarBlock == nil) {
        UUCarEditVC *editVC = [UUCarEditVC instanceOfAppropriate];
        editVC.carId = carId;
        editVC.editable = NO;
        [self.navigationController pushViewController:editVC animated:YES];
    } else {
        self.didSelectCarBlock(carId);
    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    return self.didSelectCarBlock == nil && [GetPermissionManager() checkPermission:UUPermissionFlagCarReadWrite];
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [UIAlertController presentAlertControllerWithTitle:@"确定删除该车辆吗？" message:nil doneBlock:^{
            NSNumber *carId = self.cars[indexPath.row];
            
            ShowIndicator();
            WEAK_SELF();
            [GetCarManager() asyncDeleteCarWithCarId:carId
                                       completeBlock:^(NSError *error) {
                                           HideIndicatorInView(weakSelf.view);
                                           
                                           if (error != nil) {
                                               ShowTipsOnView(error.localizedDescription, weakSelf.view);
                                           }
                                       }];
        } cancelBlock:nil];
    }
}

#pragma mark - UUCarManagerObserver methods

- (void)carManagerDidUpdateCars {
    [self reloadCars];
}

- (void)carManagerDidDeleteCars:(NSArray<NSNumber *> *)cars {
    if (self.cars.count > 0) {
        NSMutableArray<NSIndexPath *> *indexPathes = [NSMutableArray array];
        NSMutableIndexSet *indexSet = [NSMutableIndexSet new];
        for (int j = 0; j < cars.count; ++j) {
            for (int i = 0; i < self.cars.count; ++i) {
                if ([self.cars[i] isEqual:cars[j]]) {
                    [indexPathes addObject:[NSIndexPath indexPathForRow:i inSection:0]];
                    [indexSet addIndex:i];
                    break;
                }
            }
        }
        
        NSMutableArray<NSNumber *> *mutableCars = [self.cars mutableCopy];
        [mutableCars removeObjectsAtIndexes:indexSet];
        self.cars = mutableCars;
        [self.tableView deleteRowsAtIndexPaths:indexPathes
                              withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}

@end
